var data1 = []
var data2 = [{'id':'1','manufacturername':'text1','purchaseorderno':'text2','contracttype':'text3','contractunit':'text4','cdate':'text5','ddate':'text6','placeofdelivery':'text7'},{'id':'2','manufacturername':'text1','purchaseorderno':'text2','contracttype':'text3','contractunit':'text4','cdate':'text5','ddate':'text6','placeofdelivery':'text7'},
    {'id':'3','manufacturername':'text1','purchaseorderno':'text2','contracttype':'text3','contractunit':'text4','cdate':'text5','ddate':'text6','placeofdelivery':'text7'},{'id':'4','manufacturername':'text1','purchaseorderno':'text2','contracttype':'text3','contractunit':'text4','cdate':'text5','ddate':'text6','placeofdelivery':'text7'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate,indexs = 0,checkboxs =false;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
    }
})()

table.render({
    elem: '#mains'
    ,url:'billChange/selectAllCarryByPage'
    ,data:data1
    ,totalRow: true
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'billNo', title:'发票号码',sort:true,width: 200}
        ,{field:'salesContractNo', title:'合同编号',sort:true,width: 200}
        ,{field:'customerContractNo', title:'客户合同号',sort:true,width: 200}
        ,{field:'customerName', title:'客户名称',sort:true,width: 200}
        ,{field:'totalInvoiceAmount', title:'发票总额',sort:true,width: 130,totalRow: true}
        ,{field:'businessModelName', title:'业务模式',sort:true,width: 130}
        ,{field:'createDate', title:'制单日期',sort:true,width: 150,templet: "<div>{{layui.util.toDateString(d.createDate, 'yyyy-MM-dd')}}</div>"}
        ,{field:'time', title:'出运日期',sort:true,width: 150,templet: "<div>{{layui.util.toDateString(d.createDate, 'yyyy-MM-dd')}}</div>"}
        ,{field:'modeOfTransport', title:'运输方式',sort:true,width: 130}
        ,{field:'salesmanName', title:'业务员',sort:true,width: 100}
        ,{field:'whetherCreditGuarantee', title:'走信保订单',width: 100, templet: function(d){
                if(d.whetherCreditGuarantee==0){
                    return "否"
                }else if(d.whetherCreditGuarantee==1){
                    return "是(采购抬头：上海沣奇)"
                }else if(d.whetherCreditGuarantee==2){
                    return "是(采购抬头：上海源铢)"
                }else{
                    return ""
                }
            }}
        ,{field: 'creditGuaranteeAmount', width: 150, title: '信保订单金额USD', sort : true}
        ,{field:'currency', title:'币种',sort:true,width:100}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 100}
        ,{field:'usdRate', title:'美金汇率',sort:true,width: 100}
    ]]
    ,id: 'mainstableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,data:data1
            ,url:'billChange/selectCarryProductByPage'
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'productCode', title:'产品编码', sort : true}
                ,{field: 'saleContractNo', width: 120, title: '销售合同单号', sort: true}
                ,{field:'specNo', title:'规格编码', sort : true}
                ,{field:'productSpecExplanation', title:'规格说明', sort : true}
                ,{field: 'clientProductNo', title: '客户货号', sort: true}
                ,{field:'productCname', title:'中文名称', sort : true}
                ,{field:'productEname', title:'英文名称', sort : true}
                ,{field: 'productCdesc', title: '中文描述', sort: true}
                ,{field: 'productEdesc', title: '英文描述', sort: true}
                ,{field:'productNum', title:'数量', sort : true}
                ,{field:'lastAmount', title:'剩余数量', sort : true}
                ,{field:'goodsUnit', title:'单位', sort : true}
                ,{field: 'fcUnitPrice', title: '单价', sort : true}
                ,{field: 'moneySubtotal', width: 120, title: '金额小计', sort : true}
            ]]
            ,id: 'producttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].id //默认第一条信息，数据为空则id为空
            }
            ,height: 400
            ,limit:50
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
        //默认选中第一条
        // if(res.data.length != 0){
        //     var jsons = {"id":res.data[0].id,"changeList":[]}
        //     changeList.push(jsons);
        // }
    }
});

var arrayids=new Array()
//监听复选框
table.on('checkbox(mainstable)', function (data) {
    checkboxs = true;
    table.reload('producttableid', {
        data:data1
        ,where:{"id": data.data.id} //点击行ID
        ,done: function (res, curr, count) {
            var shu = 0;
            for(var i = 0;i<changeList.length;i++){
                if(changeList[i].id == data.data.id){
                    indexs = i;
                    shu ++;
                }
            }
            if(shu == 0){
                var jsons = {"id":data.data.id,"changeList":[]};
                changeList.push(jsons);
                indexs = changeList.length-1;
            }
            var child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){　　　　　　//判断当前多选框是选中还是取消选中
                arrayids.push(data.data);
                changeList[indexs].changeList = layui.table.cache["producttableid"];
            }else{
                var ids=new Array();
                for(let i in arrayids){
                    if(arrayids[i].id!=data.data.id){
                        ids.push(arrayids[i])
                    }
                }
                arrayids=ids;
                changeList[indexs].changeList = [];
            }
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            form.render('checkbox');
            layer.closeAll();    //返回数据关闭loading
        }
    }, 'data');
});

//监听复选框
table.on('checkbox(producttable)', function (obj) {
    //如果checked为false
    if (!obj.checked) {
        if(obj.type=="all"){
            changeList[indexs].changeList = [];
        }else{
            for (var i = 0; i < changeList[indexs].changeList.length; i++) {
                //如果数据中有这个数据就移除
                if (changeList[indexs].changeList[i].id == obj.data.id) {
                    changeList[indexs].changeList[i].statue=true;
                }
            }
        }
    }else{
        if(obj.type=="all"){
            changeList[indexs].changeList = layui.table.cache["producttableid"];
        }else{
            //如果没有这个数据就加进去
            for (var i = 0; i < changeList[indexs].changeList.length; i++) {
                //如果数据中有这个数据就移除
                if (changeList[indexs].changeList[i].id == obj.data.id) {
                    changeList[indexs].changeList[i].statue=false;
                }
            }
        }
    };
    var child = $("#mains").next().find('tbody tr');
    //input[type="checkbox"]
    var mainsdata = layui.table.cache["mainstableid"];
    child.each(function(index, item){
            var dataindex =  $(item).attr("data-index");
            if(mainsdata[dataindex].id == changeList[indexs].id && $(item).find('td input[type="checkbox"]')[0].checked != true){
                $(item).find('td input[type="checkbox"]')[0].checked = true;
            }
        }
    );
    form.render('checkbox');

    // form.render('checkbox');
    // table.reload('producttableid', {
    //     data:data1
    //     ,where: changeList[indexs].id//点击行ID
    //     ,done: function (res, curr, count) {
    //         var subscript = [];
    //         for(var i = 0 ;i<res.data.length;i++){
    //             for(var j = 0;j<changeList[indexs].changeList.length;j++){
    //                 if(res.data[i].id == changeList[indexs].changeList[j].id){
    //                     var k = i;
    //                     subscript.push(k);
    //                 }
    //             }
    //         }
    //         var child = $("#product").next().find('tbody input[type="checkbox"]');
    //         child.each(function(index, item){
    //             var shul = 0;
    //             for(var i = 0 ;i<subscript.length;i++){
    //                 if(index == subscript[i]){
    //                     shul++;
    //                 }
    //             }
    //             if(shul == 0){
    //                 item.checked = false;
    //             }else{
    //                 item.checked = true;
    //             }
    //         });
    //         $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
    //         form.render('checkbox');
    //         layer.close(index);    //返回数据关闭loading
    //     }
    // }, 'data');
});

//单击行事件
table.on('row(mainstable)', function (obj) {
    checkboxs = false;
    var index = layer.load(1); //添加laoding
    setTimeout(function (){
        if(checkboxs != true){
            table.reload('producttableid', {
                data:data1
                ,where: {"id":obj.data.id} //点击行ID
                ,done: function (res, curr, count) {
                    var shu = 0;
                    for(var i = 0;i<changeList.length;i++){
                        if(changeList[i].id == obj.data.id){
                            indexs = i;
                            shu ++;
                        }
                    }
                    if(shu != 0){
                        var subscript = [];
                        for(var i = 0 ;i<res.data.length;i++){
                            for(var j = 0;j<changeList[indexs].changeList.length;j++){
                                if(res.data[i].id == changeList[indexs].changeList[j].id){
                                    var k = i;
                                    subscript.push(k);
                                }
                            }
                        }
                        var child = $("#product").next().find('tbody input[type="checkbox"]');
                        child.each(function(index, item){
                            var shul = 0;
                            for(var i = 0 ;i<subscript.length;i++){
                                if(index == subscript[i]){
                                    shul++;
                                }
                            }
                            if(shul == 0){
                                item.checked = false;
                            }else{
                                item.checked = true;
                            }
                        });
                    }else{
                        var jsons = {"id":obj.data.id,"changeList":[]};
                        changeList.push(jsons);
                        indexs = changeList.length-1;
                        var child = $("#product").next().find('tbody input[type="checkbox"]');
                        child.each(function(index, item){
                            item.checked = false;
                        });
                    }
                    $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
                    form.render('checkbox');
                    layer.close(index);    //返回数据关闭loading
                }
            }, 'data');
        }
    }, 500);
});

form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        data:data1 ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {

    var purchaseorderdata =   table.checkStatus("mainstableid").data; //第一个表格选中的数据
    var main=table.checkStatus("mainstableid");
    var product=table.checkStatus("producttableid");
    var produces=new Array()
    for(let i in changeList){
        for(let j in changeList[i].changeList){
            if(!changeList[i].changeList[j].statue){
                let tmp=changeList[i].changeList[j]
                delete tmp.statue
                produces.push(tmp)
            }

        }
    }
    if(main.data.length==0&&product.data.length==0){
        layer.msg("请选择数据")
    }else{
        //执行接口
         
        var first = arrayids[0];
        var carryIds=""
        for(let i in arrayids){
            carryIds+=arrayids[i].id+","
        }
        var oldData =  parent.table.cache["storageproductstableid"];
        //将出运产品转换为报关产品，出运配件转换成报关产品
        var billProducts=null
        $.ajax({
            url: 'billChange/changeProducts',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            async: false, // 同步
            data: JSON.stringify(produces),
            success: function (date) {
                billProducts=date.data;
            }
        });
        $.each(billProducts, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i].carryProductsId== billProducts[index].carryProductsId;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //不存在重复数据,添加数据
                oldData.push(billProducts[index]);
            }
        });


        //费用
        var oldCost =  parent.table.cache["costtableid"];
        var newCost='';
        var returnCost=new Array();
        for(let i in oldCost){
            returnCost.push(oldCost[i])
        }

        //费用查询
        $.ajax({
            url: 'billChange/selectCost',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            async: false, // 同步
            data: JSON.stringify(main.data),
            success: function (date) {
                newCost =date.data;
            }
        });


        for(let i in newCost){
            var newcc=newCost[i]
            var istrue =0;//0是不重复，1是重复
            for(let i in oldCost){
                if(newcc.id==oldCost[i].id){
                    istrue=1;//重复了
                }
            }
            if(istrue==0){
                returnCost.push(newcc);
            }
        }
        parent.table.reload('costtableid', {data:returnCost});//费用信息
        //$("input[name='contact']").val();$("input[name='xxx']:checked").val();
        parent.$("input[name='businessmodel']").val(first.businessModelName);
        parent.$("input[name='contact']").val(first.salesmanName);
        var s=dateFormatter(first.createDate)
        var iDate="";
        if(first.businessModelName=="海外销售"||first.businessModelName=="海外模式"){
            $.ajax({
                url: 'billChange/selectpickupdate?billNo='+first.billNo,
                type: 'GET',
                async: false, // 同步
                success: function (date) {
                    iDate=date.data
                }
            });
            if(isEmpty(iDate)){
                layer.msg("未做销售出库，请先做销售出库")
                return false;
            }
        }else if(first.businessModelName=="正常业务"||first.businessModelName=="备货入库"||first.businessModelName=="正常模式"){
            //获取当前时间
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            if (month < 10) {
                month = "0" + month;
            }
            if (day < 10) {
                day = "0" + day;
            }
            var nowDate = year + "-" + month + "-" + day;
           iDate=nowDate
        }else{
            iDate=s
        }
        parent.$("input[name='idate']").val(iDate);
        parent.$("input[name='warehouse']").val(first.warehouseName);
        parent.$("input[name='containertype']").val(first.accountingPeriod);
        parent.$("input[name='invoicenumber']").val(first.billNo);
        var s1=dateFormatter(first.time)
        parent.$("input[name='shdate']").val(s1);
        parent.$("input[name='exchangerate']").val(first.usdRate);
        parent.$("input[name='rmbexchangerate']").val(first.rmbRate);
        parent.$("input[name='modetransportation']").val(first.modeOfTransport);
        parent.$("input[name='invoicetotalamount']").val(first.totalInvoiceAmount);
        var d = new Date();
        var str = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
        parent.$("input[name='createdate']").val(str);
        var sale=new Map()
        var cust=new Map()
        for(let i in produces){
            if(produces[i].saleContractNo!=null&&produces[i].saleContractNo!=""){
                sale.set(produces[i].saleContractNo,1);
            }
            if(produces[i].clientContractNo!=null&&produces[i].clientContractNo!=""){
                cust.set(produces[i].clientContractNo,2)
            }
        }
        var salesContractNo="";
        sale.forEach(function(value,key){
            salesContractNo+=key+"-"
        });
        var customerContractNo=""
        cust.forEach(function(value,key){
            customerContractNo+=key+"-"
        });
        if(customerContractNo=="null-"&&salesContractNo!=null){
            customerContractNo=salesContractNo
        }
        if(salesContractNo=="null-"&&customerContractNo!=null){
            salesContractNo=customerContractNo
        }
        parent.$("input[name='salescontractno']").val(salesContractNo.substr(0,salesContractNo.length-1));
        parent.$("input[name='customercontractno']").val(customerContractNo.substr(0,customerContractNo.length-1));
        var s2=dateFormatter(first.actualTimeDismissal)
        if(first.actualTimeDismissal==null){
            s2=null;
        }
        parent.$("input[name='actualdischargedateatd']").val();
        var s3=dateFormatter(first.loadingTime)
        if(first.loadingTime==null){
            s3=null;
        }
        parent.$("input[name='wldate']").val(s3);
        parent.$("input[name='salesman']").val(first.salesmanName);
        parent.$("input[name='customername']").val(first.customerName);
        parent.$("input[name='currency']").val(first.currency);
        parent.$("#place").find("option[value='"+first.transitPlaceName+"']").attr("selected",true);
        parent.$("#destination").find("option[value='"+first.destinationName+"']").attr("selected",true);
        parent.$("#settlementway").find("option[value='"+first.paymentMethodName+"']").attr("selected",true);
        parent.$("#priceterms").find("option[value='"+first.priceTermsName+"']").attr("selected",true);
        parent.$("#bank").find("option[value='"+first.bankName+"']").attr("selected",true);
        parent.$("#carryIds").val(first.id)
        parent.$("#signingcompany").val(first.signingCompanyName)
        parent.table.reload('storageproductstableid', {data:oldData});//产品信息
        parent.$("#signingcompanyCode").val(first.signingCompanyCode)
        parent.$("#salesmanCode").val(first.salesmanCode)
        parent.$("#custCode").val(first.customerCode)
        parent.$("#customerLevelName").val(first.customerLevelName)
        parent.$("#customerLevelCode").val(first.customerLevelCode)
        //预计收汇日期   =发票日期加账期
        var edrdate=""
        if(iDate!=""&&first.accountingPeriod!=null){
            d = new Date(iDate);
            d = +d + parseInt(first.accountingPeriod)*1000*60*60*24;
            d = new Date(d);
            edrdate= d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
        }
        parent.$("input[name='edrdate']").val(edrdate);
        var s="否"
        if(first.whetherCreditGuarantee==1){
            s="是(采购抬头：上海沣奇)"
        }else if (first.whetherCreditGuarantee==2){
            s="是(采购抬头：上海源铢)"
        }
        parent.$("#whetherCreditGuarantee").val(s)
        parent.$("#creditGuaranteeAmount").val(first.creditGuaranteeAmount)
        //加载附件
        $.ajax({
            url: 'billDeclare/selectBillFile?type=0&parentId='+first.id,
            type: 'GET',
            success: function (date) {
                parent.table.reload('attachmenttableid', {data:date.data});;
                parent.annexList=date.data;
            }
        });
        //加载操作员
        $.ajax({
            url: 'billDeclare/getUser',
            type: 'GET',
            success: function (date) {
                parent.$("input[name='theoperator']").val(date.data.name);//操作员及操作员编码
                parent.$("#opCode").val(date.data.code)
            }
        });
        // parent.$("#carryIds']").val(carryIds);
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
    }
})


$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

function callbackdata() {
    var produces=new Array()
    for(let i in changeList){
        for(let j in changeList[i].changeList){
            produces.push(changeList[i].changeList[j])
        }

    }
    var call={
        "firstId":arrayids[0],
        "products":produces,
    }
    return call;
}
//参数是后台返回的Object对象，不是字符串
function dateFormatter(date){
//Object对象转为日期格式
    var date=new Date(date);
    var strDate = date.getFullYear()+"-";
    var month=date.getMonth()+1;
    var day=date.getDate();
    //格式化日期,月日时分秒保持两位
    strDate=strDate+(month>8?month:"0"+month)+"-"
        +(day>9?day:"0"+day)
    return strDate ;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}